"use client";

import { v4 as uuidv4 } from "uuid";
import Icon from "../_component/icon";
import { allDriver } from "../action/driver";
import { getRouters, deleteRouter } from "../action/router";
import { useState, useEffect } from "react";
import ShowDialog from "../_component/dialog";
import RouterForm from "./router";
import { columns_name } from "./input";
import { AlertInfo } from "./alert";

export default function RouterTable() {
  const [select, Setselect] = useState(null);
  const [driverList, SetDriverList] = useState(null); // 所有驱动列表
  const [driverName, SetDriverName] = useState(null); // 当前选择的驱动名称
  const [routers, SetRouters] = useState(null);
  const [router, SetRouter] = useState(null);
  const [alert, SetAlert] = useState(null);
  const [modal, SetModal] = useState("增加路由"); // modal 对话框，增加路由或者修改路由

  const getDrivers = async () => {
    const driverList = await allDriver();
    SetDriverList(driverList);
  };

  const allRouters = async () => {
    const router_list = await getRouters();
    SetRouters(router_list);
  };

  useEffect(() => {
    getDrivers();
    allRouters();
  }, []);

  const popupDialog = (dialogName) => {
    // 设置 modal 的名字
    SetModal(dialogName);

    // 显示模态对话框
    ShowDialog("modal-dialog");

    // 设置 driver,在编辑的对话框，driver 作为默认值带入
    if (dialogName === "编辑路由") {
      const router = routers.find((router) => router.id === select);
      if (router) {
        SetDriverName(router.driver.name);
      }

      // 为模态对话框里的 driver-list 设置默认值
      const driverList = document.getElementById("driver-list");
      if (driverList) {
        driverList.value = router.driver.name;
      }
    } else {
      // 增加路由
      // 取消选择的路由和 router
      Setselect(null);
      SetRouter(null);
    }
  };

  const updateRouters = () => {
    allRouters();
  };

  const showAlert = (info) => {
    const alert = document.getElementById("router_alert");

    if (alert) {
      SetAlert(info);
      alert.classList.remove("hidden");
    }
  };

  const closeAlert = () => {
    const alert = document.getElementById("router_alert");
    if (alert && !alert.classList.contains("hidden")) {
      alert.classList.add("hidden");
    }
  };

  const deleteEvent = () => {
    if (select === null) {
      showAlert("请选择一个路由");
      return;
    }

    deleteRouter(select);
    allRouters();
  };

  const selectEvent = (id) => {
    Setselect(id);

    closeAlert();

    const router = routers.find((router) => router.id === id);

    if (router) {
      SetRouter(router);

      // set driver name
      SetDriverName(router.driver.name);
    }
  };

  return (
    <div>
      <dialog id="modal-dialog" className="modal">
        <RouterForm
          dialogName={modal}
          driverList={driverList}
          driverName={driverName}
          router={router}
          SetDriverName={SetDriverName}
          refresh={updateRouters}
        />
      </dialog>

      <section className="card bg-base-100 col-span-12 mt-2 overflow-hidden p-4 shadow-sm xl:col-span-7">
        <div className="card-body grow-0">
          <div className="flex justify-between gap-2">
            <h2 className="card-title grow">
              <div className="flex flex-col gap-1">
                <span className="card-title text-2xl">路由列表</span>
                <span className="text-sm text-gray-400">
                  路由是连接不同大模型服务的唯一标识
                </span>
              </div>
            </h2>
            <button className="btn btn-sm">
              <Icon name="refresh" color="none" />
            </button>
            <button
              className="btn btn-sm"
              onClick={() => popupDialog("增加路由")}
            >
              <Icon name="add" color="none" />
            </button>

            <button className="btn btn-sm" onClick={deleteEvent}>
              <Icon name="delete" color="none" />
            </button>

            <button
              className="btn btn-sm"
              onClick={() => popupDialog("编辑路由")}
            >
              <Icon name="edit" color="none" />
            </button>
          </div>
        </div>

        <div id="router_alert" className="hidden">
          <AlertInfo alert={alert} />
        </div>

        <div className="overflow-x-aut4 m-4">
          <table className="table-pin-rows table-pin-cols table">
            <thead>
              <tr>
                {columns_name.map((item) => (
                  <th key={uuidv4()}>{item}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {routers &&
                routers.map((item) => (
                  <tr
                    key={item.id}
                    onClick={() => selectEvent(item.id)}
                    className={select === item.id ? "bg-base-200" : ""}
                  >
                    {[
                      item.name,
                      item.driver.name,
                      item.api_key,
                      item.url,
                      item.secret_key,
                      item.access_token,
                      item.region,
                    ].map((i) => (
                      <td key={uuidv4()} className="max-w-28 truncate">
                        {i}
                      </td>
                    ))}
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
